extends CharacterBody2D
var hp:int #当前生命
@export var maxhp:int = 1 #最大生命
@export var atk:int=1 #攻击
@export var agi:int=5 #移动敏捷
@export var freq:float=1.0 #发射频率
@export var armor:int=1 #护甲
var state #状态
@onready var skin = $skin
@onready var collision = $CollisionPolygon2D
@onready var animationPlayer = $AnimationPlayer
@onready var shoot_timer = $shootTimer
@onready var hpBar = $hpBar/ProgressBar


signal status_changed



func _ready():
	state = global.STATE_ACTIVE
	hp = maxhp
	shoot_timer.wait_time = freq
	connect("status_changed", update_status)
	$animationSprite.visible=false
	
	
	hpBar.size.x = min(200, skin.get_rect().size.x)
	
	hpBar.position.x = - hpBar.size.x/2
	hpBar.position.y = - skin.get_rect().size.y/2 - 5
	print(skin.get_rect().size)
	print(hpBar.position)

func change_hp(v):
	print("change_hp="+str(v))
	if v<0:
		$damageAudio.play()
		animationPlayer.play("blink")
		
		
	hp+=v
	hp = min(hp, maxhp)
	
	emit_signal("status_changed")
	if state!=global.STATE_DEAD:
		if hp<1:
			dead()
		else:
			pass

func dead():
	state = global.STATE_DEAD
	$destroyTimer.start()
	var ex = preload("res://scene/object/explosion.tscn").instantiate()
	get_parent().add_child(ex)
	ex.position = position

func update_status():
	hpBar.value = hp


func fire(_is_enemy):
	if not _is_enemy:
		$shootAudio.play()
	
	var atk_scene = preload("res://scene/object/attack.tscn")
	for node in get_node("guns").get_children():
		
		# 直射弹
		if node.is_in_group("direct_shoot") and node.visible:
			var atk = atk_scene.instantiate()
			atk.is_enemy = _is_enemy
			atk.init_pos = node.global_position
			atk.type = 0
			get_parent().add_child(atk)
			
		# 散弹	
		if node.is_in_group("polar_shoot") and node.visible:	
			var atk = atk_scene.instantiate()
			atk.is_enemy = _is_enemy
			atk.init_pos = node.global_position
			atk.type = 1
			get_parent().add_child(atk)	
	
func _on_destroy_timer_timeout():
	#print("_on_destroy_timer_timeout")
	queue_free()


func _on_shoot_timer_timeout():
	pass # Replace with function body.


func _on_animation_player_animation_finished(anim_name):
	pass 
